import Vue from 'vue';
import Vuex from 'vuex';
import { getBanner, getNewst, getPlayerList } from '@/services';
import { playerName } from '@/filters';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    bannerNews: [],
    newstNews: [],
    playerSearchResult: [],
    defaultPlayerSearchResult: [],
    defaultFilterPlayerList: [],
  },
  mutations: {
    getBannerNews(state, data) {
      state.bannerNews = data;
    },
    getNewstNews(state, data) {
      state.newstNews = data;
    },
    getPlayerList(state, object) {
      const start = (object.page - 1) * 10;
      const end = start + 10;
      if (object.notPageChange) {
        state.defaultPlayerSearchResult = object.data;
      }
      state.playerSearchResult = object.data.slice(start, end);
      state.defaultFilterPlayerList = object.data;
    },
    filterPlayerList(state, data) {
      if (!data.name) {
        state.playerSearchResult = state.defaultPlayerSearchResult.slice(0, 10);
        state.defaultFilterPlayerList = state.defaultPlayerSearchResult;
      } else {
        const index = playerName.indexOf(data.name);
        if (index === -1) {
          state.playerSearchResult = [];
          state.defaultFilterPlayerList = [];
        } else {
          const newPlayerList = state.defaultPlayerSearchResult;
          state.defaultFilterPlayerList = newPlayerList.filter(x => x.name === index + 1);
          state.playerSearchResult = newPlayerList.filter(x => x.name === index + 1).slice(0, 10);
        }
      }
    },
    emptyPlayerList(state) {
      state.playerSearchResult = [];
      state.defaultPlayerSearchResult = [];
      state.defaultFilterPlayerList = [];
    },
  },
  actions: {
    async getBannerNews({ commit }) {
      commit('getBannerNews', await getBanner());
    },
    async getNewstNews({ commit }) {
      commit('getNewstNews', await getNewst());
    },
    async searchPlayerResult({ commit, state }, object) {
      commit(
        'getPlayerList',
        {
          data: object.notPageChange ? await getPlayerList() : state.defaultFilterPlayerList,
          ...object,
        },
      );
    },
  },
});

export default store;
